package com.nsharmon.iBridge.beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.nsharmon.iBridge.dao.EMF;
import com.nsharmon.iBridge.dao.entities.User;

@ManagedBean
@SessionScoped
public class Identity {
	private User user = null;
	
	public String getLogoutUrl() {
		UserService userService = UserServiceFactory.getUserService();
		return userService.createLogoutURL("/index.jsf");
	}

	public String getLoginUrl() {
		ExternalContext ctx = FacesContext.getCurrentInstance()
				.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ctx.getRequest();
		HttpServletResponse response = (HttpServletResponse) ctx.getResponse();

		UserService userService = UserServiceFactory.getUserService();
		return userService.createLoginURL(response.encodeURL(request
				.getRequestURI()));
	}
	
	public User getCurrentUser() {
		if(user == null && isLoggedIn()) {
			UserService userService = UserServiceFactory.getUserService();
			com.google.appengine.api.users.User gUser = userService.getCurrentUser();
			
			user = loadUser(gUser);
		}
		return user;
	}
	
	private User loadUser(com.google.appengine.api.users.User gUser) {
		EntityManager em = EMF.createEntityManager();
		Query q = em.createQuery("SELECT u FROM User u WHERE u.userId = ?1");
		q.setParameter(1, gUser.getUserId());
		
		User user = (User)q.getSingleResult();
		if(user == null) {
			user = new User();
			user.setUserId(gUser.getUserId());
		}		
		if(user.getId() == null) {
			em.persist(user);
		}	
		em.close();		
		return user;
	}

	public boolean isLoggedIn() {
		UserService userService = UserServiceFactory.getUserService();
		return userService.isUserLoggedIn();
	}
}